﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using Lamex.Base;

namespace Lamex.Library.UserCotrolUI
{
    public partial class FrmProductRate : UserControl
    {
        public FrmProductRate()
        {
            InitializeComponent();
        }

        public void ShowProcessList(string ProcessCode, int iStandTime,string UserName)
        {
            try
            {
                if (string.IsNullOrEmpty(ProcessCode))
                {
                    XtraMessageBox.Show("没有输入工序号");
                    return;
                }


                DataTable dtItme = BaseBuildSql.GetDataTableBySql(@" select a.* from  [dbo].[HR_Work_ShiftRec]  a 
 join (select top 1* from  [HR_Station_Info]  where STATION_NAME='" + UserName + @"') b on b.DEPARTMENT=a.DEPARTMENT
 where   a.EFFECTIVE_DATE<  CONVERT(nvarchar(10),GETDATE(),120) and CONVERT(nvarchar(10),GETDATE(),120)<CONVERT(nvarchar(10), a. EXPIRY_DATE,120)
                                                                ");
                string[] strArrayTime = dtItme.Rows[0]["T1_START"].ToString().Split(':');
                string time = DateTime.Now.ToString("yyyy -MM-dd");
                string startday = DateTime.Now.ToString("yyyy-MM-dd");
                string timestart1 = "";
                string timestart2 = "";
                string timestart3 = "";
                string timesEnd1 = "";
                string timesEnd2 = "";
                string timesEnd3 = "";
                if (dtItme.Rows.Count != 0)
                {
                    time = time + " " + dtItme.Rows[0]["T1_START"].ToString();
                    timestart1 = startday + " " + dtItme.Rows[0]["T1_START"].ToString();
                    timestart2 = startday + " " + dtItme.Rows[0]["T2_START"].ToString();
                    timestart3 = startday + " " + dtItme.Rows[0]["T3_START"].ToString();
                    timesEnd1 = startday + " " + dtItme.Rows[0]["T1_END"].ToString();
                    timesEnd2 = startday + " " + dtItme.Rows[0]["T2_END"].ToString();
                    timesEnd3 = startday + " " + dtItme.Rows[0]["T3_END"].ToString();

                }
                else
                {
                    XtraMessageBox.Show("没有员工排班表");
                    return;
                }
                DateTime startTime1 = Convert.ToDateTime(timestart1);
                DateTime startTime2 = Convert.ToDateTime(timestart2);
                DateTime startTime3 = Convert.ToDateTime(timestart3);

                DateTime endTime1 = Convert.ToDateTime(timesEnd1);
                DateTime endTime2 = Convert.ToDateTime(timesEnd2);
                DateTime endTime3 = Convert.ToDateTime(timesEnd3);
                DateTime startTime = DateTime.Now;
                decimal hour1 = 0;
                decimal hour2 = 0;
                decimal hour3 = 0;
                #region"计算当前时间的数据值"
                if (endTime1 > startTime)
                {
                    TimeSpan span = startTime.Subtract(startTime1);
                    hour1 = Convert.ToDecimal(span.Hours) + Convert.ToDecimal(span.Minutes) / 60;
                }
                else if (endTime1 < startTime && startTime2 > startTime)
                {
                    TimeSpan span = endTime1.Subtract(startTime1);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (startTime2 < startTime && startTime < endTime2)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + startTime.Subtract(startTime2);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (endTime2 < startTime && startTime < startTime3)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + endTime2.Subtract(startTime2);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (startTime3 < startTime && startTime < endTime3)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + endTime2.Subtract(startTime2) + startTime.Subtract(startTime3);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (endTime3 < startTime)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + endTime2.Subtract(startTime2) + endTime3.Subtract(startTime3);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                #endregion

                string local = UserName+"_09";
                DataTable dtPass = BaseBuildSql.GetDataTableBySql(@"
 select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and STATION_NAME='" + UserName + @"'  group by CONVERT(nvarchar(6),BARCODE)
union all
select m.SCAN_QTY- case when isnull(n.SCAN_QTY,'')=''then 0 else n.SCAN_QTY end SCAN_QTY,m.MES_PD from (select sum(SCAN_QTY) SCAN_QTY,'MES_PD' as MES_PD from HR_Scan_Record s
left join HR_Station_Info i on i.LOCATION_NAME=s.LOCATION_CODE
where i.LOCATION_CODE='" + local + @"' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and s.STATION_NAME='"+UserName+ @"'
group by i.LOCATION_CODE) m 
left join (select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE,'MES_PD' as MES_PD from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120)  and STATION_NAME='" + UserName + @"' group by CONVERT(nvarchar(6),BARCODE)
) n on n.MES_PD=m.MES_PD
                                                                ");
                if (dtPass.Rows.Count == 0)
                {
                    //XtraMessageBox.Show("扫描表还没有数据!");
                    return;
                }
                string dt3Sum = dtPass.Compute("sum(SCAN_QTY)", "true").ToString();
                if (string.IsNullOrEmpty(dt3Sum)) return;
                if (int.Parse(dt3Sum) == 0) return;

                DataRow dr = dtPass.Select(" 1=1 and BARCODE='MES_PD'").FirstOrDefault();

                if (dr == null) return;
                decimal quality = decimal.Parse(dr["SCAN_QTY"].ToString()) / hour1;
                //time = time + ":00:00:000";
                DateTime dates = Convert.ToDateTime(time);
                List<string> lst = new List<string>();

                DataTable dtProcess = null;
                if (strArrayTime[1] == "00")
                {
                    dates = dates.AddHours(1);

                    lst.Add(dates.ToString());
                    lst.Add(endTime3.AddHours(1).ToString());
                    lst.Add(iStandTime.ToString());
                    lst.Add(UserName + "_09");
                    dtProcess = BaseBuildSql.GetProDataTable("P_GetProductRateNew2", lst);
                }

                else
                {
                    dates = dates.AddHours(-1);
                    lst.Add(dates.ToString());
                    lst.Add(endTime3.AddHours(1).ToString());
                    lst.Add(iStandTime.ToString());
                    lst.Add(UserName + "_09");
                    dtProcess = BaseBuildSql.GetProDataTable("P_GetProductRateSource", lst);
                }
                string ProcessName = "工位" + ProcessCode;


                chartProductRate.Series.Clear();

                Series seriesAuto = new Series("", ViewType.Line);
                seriesAuto.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;

                foreach (DataRow drow in dtProcess.Rows)
                {


                    //dr["Title"] = percent;
                    string StatusName = "";
                    SeriesPoint p = new SeriesPoint();

                    double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(drow["SCAN_QTYRATE"].ToString())), 2).ToString()) };
                    //p.Values
                    if (decimal.Parse(drow["SCAN_QTYRATE"].ToString()) != 0)
                        p.Values = d;

                    string percent = drow["TIMES"].ToString();
                    p.Argument = percent;

                    seriesAuto.Points.Add(p);
                }
                seriesAuto.DataSource = dtProcess;
                seriesAuto.LabelsVisibility = DevExpress.Utils.DefaultBoolean.False; ;

                //seriesAuto.ArgumentScaleType = ScaleType.Qualitative;
                //名称
                //seriesAuto.ArgumentDataMember = "TIMES";

                //seriesAuto.ValueScaleType = ScaleType.Qualitative;


                //seriesAuto.Visible = false;
                //取值字段 
                //seriesAuto.ValueDataMembers.AddRange(new string[] { "SCAN_QTYRATE" });
                //(seriesAuto.Label as PieSeriesLabel).Position = PieSeriesLabelPosition.Outside;
                //显示标项目名称和百分比数据
                //seriesAuto.PointOptions.PointView = PointView.ArgumentAndValues;
                //seriesAuto.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;





                this.chartProductRate.Series.Add(seriesAuto);

                XYDiagram diagramhour = (XYDiagram)chartProductRate.Diagram;
                diagramhour.AxisY.ConstantLines.Clear();
                //diagramhour.EnableAxisXScrolling = true;
                //diagramhour.EnableAxisXZooming = true;
                //diagramhour.EnableAxisYScrolling = true;
                //diagramhour.EnableAxisYZooming = true;
                diagramhour.AxisX.QualitativeScaleOptions.AutoGrid = false;
                diagramhour.AxisX.Label.ResolveOverlappingOptions.AllowHide = false;
                diagramhour.AxisY.WholeRange.MaxValue = 1.2;
                diagramhour.AxisY.WholeRange.MinValue = 0;

                //diagramhour.AxisY.VisualRange.MinValue = iStandTime * 0.75;
                ////diagramhour.AxisY.VisualRange.MaxValue = 250;
                ////diagramhour.AxisY.VisualRange.SideMarginsValue = 10;
                //diagramhour.AxisY.WholeRange.MaxValue = 260;
                //diagramhour.AxisY.WholeRange.MinValue = 150;
                //diagramhour.AxisY.WholeRange.AlwaysShowZeroLevel = true;
                //diagramhour.AxisY.WholeRange.SideMarginsValue = 1;

                //diagramhour.AxisY.Logarithmic = true;
                //diagramhour.AxisY.LabelVisibilityMode = AxisLabelVisibilityMode.Default;
                //diagramhour.AxisY.LogarithmicBase=10;
                // diagramhour.AxisX.WholeRange.MinValue = 30;
                //diagramhour.AxisX.Interlaced = true;
                //diagramhour.AxisX.Label = 10
                //diagramhour.AxisX.WholeRange.MaxValue= 150;
                //diagramhour.AxisX.WholeRange.MinValue = 0;
                //diagramhour.AxisX.Logarithmic = true;
                //diagramhour.AxisX.LogarithmicBase = 5;
                decimal iStander = decimal.Parse(dr["SCAN_QTY"].ToString()) / (3600 * hour1 / decimal.Parse(iStandTime.ToString()));//当前时间当前产品应完成数量;
                ConstantLine constantLineligh = new ConstantLine((Math.Round(iStander * decimal.Parse((8.0 / 7.5).ToString()), 2) * 100).ToString() + "%", Math.Round(iStander * decimal.Parse((8.0 / 7.5).ToString()), 2));
                //当前小时效率


                if (Math.Round(iStander, 2) * 100 > 95)
                {
                    constantLineligh.Color = Color.Green; //直线颜色
                    constantLineligh.Title.TextColor = Color.Green;   //直线文本字体颜色  
                }
                else
                {
                    constantLineligh.Color = Color.Red; //直线颜色
                    constantLineligh.Title.TextColor = Color.Red;   //直线文本字体颜色  
                }
                constantLineligh.Title.Visible = true;
                constantLineligh.ShowInLegend = false;

                diagramhour.AxisY.ConstantLines.Add(constantLineligh);

                ConstantLine constantLineligh1 = new ConstantLine("目标100%", 1);
                //当前小时效率
                constantLineligh1.Color = Color.Green; //直线颜色
                constantLineligh1.Title.TextColor = Color.Green;   //直线文本字体颜色  
                constantLineligh1.Title.Alignment = ConstantLineTitleAlignment.Far;
                constantLineligh1.Title.Visible = true;
                constantLineligh.ShowInLegend = false;

                diagramhour.AxisY.ConstantLines.Add(constantLineligh1);

                //横标题设置
                //chartProductRate.Titles.Clear();
                //ChartTitle titles = new ChartTitle();            //声明标题
                //titles.Text = ProcessName;                            //名称
                //                                                      //titles.TextColor = System.Drawing.Color;   //颜色
                //titles.Indent = 1;                                //设置距离  值越小柱状图就越大
                //titles.Font = new Font("Tahoma", 12, FontStyle.Bold);            //设置字体
                //titles.Dock = ChartTitleDockStyle.Top;           //设置对齐方式
                //titles.Indent = 0;
                //titles.Alignment = StringAlignment.Center;       //居中对齐
                //chartProductRate.Titles.Add(titles);                 //添加标题  
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message+"productRate");
            }

        }
    }
}
